/**
 *<p>****************************************************************************</p>
 * <p><b>Copyright © 2010-2018 soho team All Rights Reserved<b></p>
 * <ul style="margin:15px;">
 * <li>Description : 数据请求公共封装</li>
 * <li>Version     : 1.0</li>
 * <li>Creation    : 2018年08月02日</li>
 * <li>@author     : ____′↘夏悸</li>
 * </ul>
 * <p>****************************************************************************</p>
 */
import axios from 'axios';
import Qs from 'qs';
import utils from '../utils';

axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

const axios0 = axios.create({
  baseURL: utils.baseUrl,
  headers: {'Content-type': 'application/x-www-form-urlencoded'}
});

const changeLoading = (vm, val) => {
  if (vm.hasOwnProperty('loading')) {
    vm.loading = val;
  }
};

class xhr {
  constructor(vm) {
    this.$vm = vm;
  }

  request(config) {
    return new Promise((resolve, reject) => {
      try {
        changeLoading(this.$vm, true);
        axios0.request(config).then(({data}) => {
          changeLoading(this.$vm, false);
          if (data.success) {
            resolve(data);
          } else {
            this.$vm.$snotify.error(data.msg);
            reject(data);
          }
        }).catch(reason => {
          console.log(reason);
          if (reason.response.status === 401) {
            this.$vm.$router.replace({name: 'Login'});
          } else if (reason.response.status === 403) {
            this.$vm.$router.replace({name: 'Reject'});
          } else {
            changeLoading(this.$vm, false);
            this.$vm.$snotify.error(reason.message);
            reject(reason);
          }
        });
      } catch (e) {
        changeLoading(this.$vm, false);
        this.$vm.$snotify.error(e.message);
        reject(e);
      }
    });
  }

  get(url, params = {}, config = {}) {
    config.url = url;
    config.params = params;
    return this.request(Object.assign(config, {method: 'get'}));
  }

  post(url, data, config = {}) {
    config.url = url;
    config.data = Qs.stringify(data, Object.assign({allowDots: true, arrayFormat: 'indices'}, config.qs));
    return this.request(Object.assign(config, {method: 'post'}));
  }

  delete(url, params = {}, config = {}) {
    config.url = url;
    config.params = params;
    return this.request(Object.assign(config, {method: 'delete'}));
  }

  upload(url, data, config = {}) {
    config.url = url;
    config.data = data;
    return this.request(Object.assign(config, {method: 'post'}));
  }
}

export default xhr;
